package com.nccsjz.back.section.web;

import java.io.File;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

import utils.ConfigUtils;
import utils.FileUtils;

import com.nccsjz.back.section.service.SectionService;
import com.nccsjz.back.section.utils.LevelOneUtils;
import com.nccsjz.back.section.utils.LevelTwoUtils;
import com.nccsjz.base.BaseAction;
import com.nccsjz.pojo.Section;

@SuppressWarnings("serial")
public class SectionAction extends BaseAction {

	/** PATH_LIST_LEVEL_ONE String 返回section.jsp逻辑路径 */
	private static final String PATH_LIST_LEVEL_ONE = "listLevelOne";

	/** PATH_LIST_LEVEL_TWO String 返回leveltwo.jsp逻辑路径 */
	private static final String PATH_LIST_LEVEL_TWO = "listLevelTwo";

	/** PATH_LEVEL_TWO_INPUT 返回leveltwoinput.jsp逻辑路径 */
	private static final String PATH_LEVEL_TWO_INPUT = "levelTwoInput";

	/** PATH_LEVEL_TWO_EDIT 返回leveltwoedit.jsp逻辑路径 */
	private static final String PATH_LEVEL_TWO_EDIT_INPUT = "levelTwoEdit";

	/** sections List<Section> 栏目列表 */
	private List<Section> sections;

	/** section Section 封装表单中的栏目信息 **/
	private Section section;

	/** dynamic String 标识添加的二级栏目是否是动态页面 */
	private String dynamicCheck;

	public List<Section> getSections() {
		return sections;
	}

	public void setSections(List<Section> sections) {
		this.sections = sections;
	}

	public Section getSection() {
		return section;
	}

	public void setSection(Section section) {
		this.section = section;
	}

	public String getDynamicCheck() {
		return dynamicCheck;
	}

	public void setDynamicCheck(String dynamicCheck) {
		this.dynamicCheck = dynamicCheck;
	}

	/**
	 * listLevelOne方法用于处理初始化一级栏目列表操作
	 * 
	 * @return 逻辑路径
	 */
	public String listLevelOne() throws Exception {
		sections = new SectionService().listLevelOne();
		return PATH_LIST_LEVEL_ONE;
	}

	/**
	 * listLevelTwo方法用于处理初始化二级栏目列表的操作
	 * 
	 * @return
	 * @throws Exception
	 */
	public String listLevelTwo() throws Exception {
		// 根据一级栏目编号查询栏目标题
		SectionService sectionService = new SectionService();
		Section s = sectionService.findById(section.getSectionId());
		section.setTitle(s.getTitle());
		// 根据一级栏目编号查询二级栏目
		sections = sectionService.listLevelTwo(section.getSectionId());
		return PATH_LIST_LEVEL_TWO;
	}

	/**
	 * addLevelOne方法用于添加一级栏目信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String addLevelOne() throws Exception {
		SectionService service = new SectionService();
		String title = section.getTitle();
		String folderName = section.getFolderName();
		if (null != service.findLevelOneByTitleOrFolderName(title, folderName)) {
			addActionError(StringUtils.join(new String[] { "标题为[", title,
					"]或文件夹为[", folderName, "]的一级栏目已经存在！" }));
		} else {
			// 创建一级栏目目录和相关Js文件的内容
			String levelOneRealDirPath = getContextRealPath(folderName);// 一级栏目目录
			// 向数据库中添加一级目录
			service.addLevelOne(section, levelOneRealDirPath,
					getLevelOneJsRealFileName());
			addActionMessage("一级栏目添加成功！");
		}
		sections = service.listLevelOne();
		return PATH_LIST_LEVEL_ONE;
	}

	/**
	 * editLevelOne方法用于更新一级栏目的信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String editLevelOne() throws Exception {
		SectionService sectionService = new SectionService();
		Section s = sectionService.findById(section.getSectionId());
		if (null == s) {
			addActionError("要更新的一级栏目已不存在，请重新选择！");
			sections = sectionService.listLevelOne();
		} else if (StringUtils.equals(s.getTitle(), section.getTitle())
				&& StringUtils.equals(s.getFolderName(), section
						.getFolderName())) {
			addActionError("要更新的一级栏目已经存在，请重新执行更新操作！");
			sections = sectionService.listLevelOne();
		} else {
			// 重新创建一级栏目目录
			String targetDirName = getContextRealPath(section.getFolderName());
			String sourceDirName = getContextRealPath(s.getFolderName());
			FileUtils.renameDir(sourceDirName, targetDirName);
			s.setTitle(section.getTitle());
			// 更改文件名
			String newFileName = StringUtils.isBlank(s.getFileName()) ? null
					: (s.getFileName().replace(s.getFolderName(), section
							.getFolderName()));
			s.setFileName(newFileName);
			String oldFolderName = s.getFolderName();
			s.setFolderName(section.getFolderName());
			String levelTwoRealPathJsFileName = StringUtils.join(new String[] {
					getLevelTwoJsRealPath(section.getFolderName()),
					File.separator, getLevelTwoJsFileName() });
			sectionService.editLevelOne(s, sourceDirName, targetDirName,oldFolderName,
					getLevelOneJsRealFileName(), levelTwoRealPathJsFileName);
			sections = sectionService.listLevelOne();
			addActionMessage("一级栏目更新成功！");
		}

		return PATH_LIST_LEVEL_ONE;
	}

	/**
	 * deleteLevelOne方法用于删除指定的栏目信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String deleteLevelOne() throws Exception {
		SectionService sectionService = new SectionService();
		// 从数据库中删除指定的一级栏目
		Section s = sectionService.findById(section.getSectionId());
		String levelOneRealDirPath = getContextRealPath(s.getFolderName());
		sectionService.deleteLevelOne(section.getSectionId(),
				levelOneRealDirPath, getLevelOneJsRealFileName());
		sections = sectionService.listLevelOne();
		addActionMessage("一级栏目删除成功！");
		return PATH_LIST_LEVEL_ONE;
	}

	/**
	 * 
	 * @param path
	 * @return
	 */
	private String getLevelTwoJsRealPath(String path) {
		String levelTwoJsRealPath = getContextRealPath(path);
		return levelTwoJsRealPath;
	}

	/**
	 * 
	 * @return
	 */
	private String getLevelTwoJsFileName() {
		String levelTwoJsFileName = ConfigUtils.getAppConfig("levelTwoJsName");
		return levelTwoJsFileName;
	}

	/**
	 * LevleOneJsRealFileName方法获得levelone.js文件的物理文件名
	 * 
	 * @return
	 */
	private String getLevelOneJsRealFileName() {
		return StringUtils.join(new String[] {
				getContextRealPath(ConfigUtils.getAppConfig("levelOneJsPath")),
				File.separator, ConfigUtils.getAppConfig("levelOneJsName") });
	}

	/**
	 * getLevelTowDynamicPageInfoMap方法获取二级栏目中的动态页面信息
	 * 
	 * @return
	 */
	public Map<String, String> getLevelTwoDynamicPageInfoMap() {
		Map<String, String> maps = new Hashtable<String, String>();
		ResourceBundle levelsTwoConfig = ConfigUtils.getLevelTwosConfig();
		Set<String> keySet = levelsTwoConfig.keySet();
		String[] arrKeys = keySet.toArray(new String[] {});
		for (String key : arrKeys) {
			maps.put(key, levelsTwoConfig.getString(key));
		}
		return maps;
	}

	/**
	 * levelTwoInput方法用于处理跳转至leveltwoinput.jsp
	 * 
	 * @return String 逻辑路径
	 * @throws Exception
	 */
	public String levelTwoInput() throws Exception {
		if (null == section || null == section.getSectionId()) {
			return PATH_LIST_LEVEL_TWO;
		}
		// 获取一级栏目标题
		SectionService sectionService = new SectionService();
		Section s = sectionService.findById(section.getSectionId());
		section.setTitle(s.getTitle());
		return PATH_LEVEL_TWO_INPUT;
	}

	/**
	 * addLevelTwo方法用于添加二级栏目
	 * 
	 * @return
	 * @throws Exception
	 */
	public String addLevelTwo() throws Exception {
		SectionService sectionService = new SectionService();
		// 查询所属一级标题
		Section levelOne = sectionService.findById(section.getParentId());
		// 设置Section的信息
		// 设置fileName
		String levelTwoFileName = null;
		if (StringUtils.equals(dynamicCheck, "on")) {
			levelTwoFileName = StringUtils.join(new String[] {
					"common", "/", section.getFileName() });
			section.setStatus(1);// 禁止修改
		} else {
			levelTwoFileName = StringUtils.join(new String[] {
					levelOne.getFolderName(), "/", section.getFileName(),
					".html" });
			section.setStatus(0);
		}
		section.setFileName(levelTwoFileName);
		// 检查是否已经存在相同标题的二级栏目
		if (sectionService.findLevelTwoByTitleOrFileNameAndParentId(section
				.getTitle(), section.getFileName(), section.getParentId()) != null) {
			addActionError(StringUtils.join(new String[] { "标题为[",
					section.getTitle(), "]或文件名为[", section.getFileName(),
					"]的二级栏目已经存在，请重新添加！" }));
			sections = sectionService.listLevelTwo(section.getParentId());
			section = (Section) BeanUtils.cloneBean(levelOne);
			return PATH_LEVEL_TWO_INPUT;
		}
		String staticRealPathFileName = null;
		String templateRealPathFileName = null;
		if (!StringUtils.equals(dynamicCheck, "on")) {
			staticRealPathFileName = getContextRealPath(levelTwoFileName
					.replace('/', File.separatorChar));
			templateRealPathFileName = getContextRealPath(ConfigUtils
					.getAppConfig("templatePath"));
		}
		String levelTwoRealPathJsFileName = StringUtils.join(new String[] {
				getLevelTwoJsRealPath(levelOne.getFolderName()),
				File.separator, getLevelTwoJsFileName() });
		sectionService.addLevelTwo(section, levelTwoRealPathJsFileName,
				staticRealPathFileName, templateRealPathFileName,
				getLevelOneJsRealFileName());
		sections = sectionService.listLevelTwo(section.getParentId());
		section = (Section) BeanUtils.cloneBean(levelOne);
		addActionMessage("二级栏目添加成功！");
		return PATH_LIST_LEVEL_TWO;
	}

	/**
	 * 
	 * @return
	 */
	public String deleteLevelTwo() throws Exception {
		SectionService sectionService = new SectionService();
		Section levelTwo = sectionService.findById(section.getSectionId());
		sections = sectionService.listLevelTwo(section.getParentId());
		Section levelOne = sectionService.findById(section.getParentId());
		String deleteFileName = StringUtils.join(new String[] {
				getContextRealPath(""),
				levelTwo.getFileName().replace("/", File.separator) });
		String levelTwoRealPathJsFileName = StringUtils.join(new String[] {
				getLevelTwoJsRealPath(levelOne.getFolderName()),
				File.separator, getLevelTwoJsFileName() });
		String levelOneRealDir = getContextRealPath(levelOne.getFolderName());
		sectionService.deleteLevelTwo(section.getSectionId(), deleteFileName,
				levelOneRealDir, levelTwoRealPathJsFileName,
				getLevelOneJsRealFileName());
		section = sectionService.findById(levelTwo.getParentId());
		sections = sectionService.listLevelTwo(levelOne.getSectionId());
		addActionMessage("二级栏目删除成功！");
		return PATH_LIST_LEVEL_TWO;
	}

	/**
	 * levelTwoEditInput方法用于处理跳转至leveltwoedit.jsp页面
	 * 
	 * @return
	 * @throws Exception
	 */
	public String levelTwoEditInput() throws Exception {
		SectionService sectionService = new SectionService();
		section = sectionService.findById(section.getSectionId());
		if (section.getStatus() == 1) {
			dynamicCheck = "on";
		} else {
			dynamicCheck = null;
		}
		return PATH_LEVEL_TWO_EDIT_INPUT;
	}

	/**
	 * editLevelTwo方法用于处理二级栏目的更新操作
	 * 
	 * @return
	 * @throws Exception
	 */
	public String editLevelTwo() throws Exception {
		SectionService sectionService = new SectionService();
		// 查询所属一级栏目
		Section levelOne = sectionService.findById(section.getParentId());
		// 查询二级栏目
		Section levelTwo = sectionService.findById(section.getSectionId());
		// 设置Section的信息
		// 设置fileName
		String levelTwoFileName = null;
		if (StringUtils.equals(dynamicCheck, "on")) {
			levelTwoFileName = StringUtils.join(new String[] {
					levelOne.getFolderName(), "/", section.getFileName() });
			levelTwo.setStatus(1);// 禁止修改
		} else {
			levelTwoFileName = section.getFileName();
			levelTwo.setStatus(0);
		}		
		levelTwo.setTitle(section.getTitle());
		String orgStaticRealPathFileName = getContextRealPath(levelTwo
				.getFileName().replace('/', File.separatorChar));
		levelTwo.setFileName(levelTwoFileName);
		levelTwo.setFileContent(section.getFileContent());
		String staticRealPathFileName = null;
		String templateRealPathFileName = null;
		if (!StringUtils.equals(dynamicCheck, "on")) {
			staticRealPathFileName = getContextRealPath(levelTwoFileName
					.replace('/', File.separatorChar));
			templateRealPathFileName = getContextRealPath(ConfigUtils
					.getAppConfig("templatePath"));
		}
		String levelTwoRealPathJsFileName = StringUtils.join(new String[] {
				getLevelTwoJsRealPath(levelOne.getFolderName()),
				File.separator, getLevelTwoJsFileName() });
		sectionService.editLevelTwo(levelTwo, levelTwoRealPathJsFileName,
				orgStaticRealPathFileName, staticRealPathFileName,
				templateRealPathFileName, getLevelOneJsRealFileName());		
		sections = sectionService.listLevelTwo(section.getParentId());
		section = (Section) BeanUtils.cloneBean(levelOne);
		addActionMessage("二级栏目[" + levelTwo.getTitle() + "］的信息更新成功！");
		return PATH_LIST_LEVEL_TWO;
	}
}
